package cn.itsource.hrm.exception;

import cn.itsource.hrm.util.AjaxResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;


//@ControllerAdvice  此注解的类会在controler类执行之前或者执行之后，处理一些逻辑
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(GlobalException.class)
    public AjaxResult globalException(GlobalException e){
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        allErrors.forEach(error->{
            sb.append(error.getDefaultMessage()).append(";");
        });

        return AjaxResult.me().setSuccess(false).setMessage(sb.toString());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult globalException(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("噢哟，系统崩溃咯，我们认真的殴打程序员！！");
    }
}
